package com.nmgs.util;

import com.nmgs.entity.WebApp;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;

@Component
public class TomcatWebUtil {
    private String port = PropertiesUtil.getValue("server.port");
    public String hostAddress = PathUtil.hostAddress;
    //    public String charset = "iso-8859-1";
    public String charset = "UTF-8";

    /**
     * 获取tomcat正在运行的webApp的参数
     *
     * @return
     */
    public ArrayList<WebApp> getTomcatWebAppData() {
        port = PropertiesUtil.getValue("server.port");
        ArrayList<WebApp> webAppArrayList = new ArrayList<WebApp>();
        String data = TomcatHTMLUtil.message("http://localhost:" + port + "/manager/text/list");
        String[] oldDataStrs = data.split("/");
        if (oldDataStrs[0].startsWith("OK")) {
            for (int i = 0; i < oldDataStrs.length; i++) {
                String name = oldDataStrs[i].split(":")[0];
                if (oldDataStrs[i].split(":").length > 1) {
                    WebApp webApp = new WebApp();
                    webApp.setName(name);
                    if (oldDataStrs[i].split(":")[1].equals("running")) {
                        try {
                            if (Integer.parseInt(oldDataStrs[i].split(":")[2]) >= 0) {
                                webApp.setStatus("运行");
                            } else {
                                webApp.setStatus("异常");
                            }
                        } catch (Exception e) {
                            webApp.setStatus("异常");
                        }
                    } else if (oldDataStrs[i].split(":")[1].equals("stopped")) {
                        try {
                            if (Integer.parseInt(oldDataStrs[i].split(":")[2]) == 0) {
                                webApp.setStatus("停止");
                            } else {
                                webApp.setStatus("异常");
                            }
                        } catch (Exception e) {
                            webApp.setStatus("异常");
                        }
                    } else {
                        webApp.setStatus("异常");
                    }
                    webAppArrayList.add(webApp);
                }
            }
        }
        return webAppArrayList;
    }

    /**
     * 重新部署一个项目
     *
     * @param webAppName
     * @return
     */
    public boolean reloadWebApp(String webAppName) {
        String data = TomcatHTMLUtil.message("http://localhost:" + port + "/manager/text/reload?path=/" + webAppName);
        if (data.startsWith("OK")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 停止一个项目
     *
     * @param webAppName
     * @return
     */
    public boolean stopWebApp(String webAppName) {
        String data = TomcatHTMLUtil.message("http://localhost:" + port + "/manager/text/stop?path=/" + webAppName);
        if (data.startsWith("OK")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据指定的path部署并启动一个新的应用程序
     */
    public boolean deployWebApp(String path, File war, boolean update) throws Exception {
        StringBuilder buffer = new StringBuilder();
        buffer.append("?path=").append(URLEncoder.encode(path, charset));
        if (war != null) {
            buffer.append("&war=").append(URLEncoder.encode(war.toString(), charset));
        }
        if (update) {
            buffer.append("&update=true");
        }
        String data = TomcatHTMLUtil.message("http://localhost:" + port + "/manager/text/deploy" + buffer);
        if (data.startsWith("OK")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 真正发送请求的方法
     */
//    private TomcatManagerResponse invoke(String path) throws Exception {
//        HttpRequestBase httpRequestBase = new HttpGet("http://" + hostAddress + ":" + port + "/manager/text" + path);
//        HttpResponse response = httpClient.execute(httpRequestBase, localContext);
//        int statusCode = response.getStatusLine().getStatusCode();
//        switch (statusCode) {
//            case HttpStatus.SC_OK: // 200
//            case HttpStatus.SC_CREATED: // 201
//            case HttpStatus.SC_ACCEPTED: // 202
//                break;
//            case HttpStatus.SC_MOVED_PERMANENTLY: // 301
//            case HttpStatus.SC_MOVED_TEMPORARILY: // 302
//            case HttpStatus.SC_SEE_OTHER: // 303
//                String redirectUrl = getRedirectUrl(response);
//                this.url = new URL(redirectUrl);
//                return invoke(path);
//        }
//        TomcatManagerResponse TomcatManagerResponse = new TomcatManagerResponse();
//        TomcatManagerResponse.setStatusCode(response.getStatusLine().getStatusCode());
//        TomcatManagerResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());
//        TomcatManagerResponse.setHttpResponseBody(IOUtils.toString(response.getEntity().getContent()));
//        return TomcatManagerResponse;
//    }

    /**
     * 卸载一个项目
     *
     * @param webAppName
     * @return
     */
    public boolean undeployWebApp(String webAppName) {
        String data = TomcatHTMLUtil.message("http://localhost:" + port + "/manager/text/undeploy?path=/" + webAppName);
        if (data.startsWith("OK")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 开始一个项目
     *
     * @param webAppName
     * @return
     */
    public boolean startWebApp(String webAppName) {
        String data = TomcatHTMLUtil.message("http://localhost:" + port + "/manager/text/start?path=/" + webAppName);
        if (data.startsWith("OK")) {
            return true;
        } else {
            return false;
        }
    }
}
